import React, {useEffect, useRef, useState} from 'react';
import "./styles/style.css"
import {Divider, Radio, message, Space, Menu, Dropdown, Select, Slider, Col, InputNumber, Row} from "antd";
import ChatListBox from "./components/ChatList";
import ChatContent from "./components/ChatContent";
import {config} from "../../config";
import useDeepCompareEffect from "use-deep-compare-effect";
import {Option} from "antd/es/mentions";
import {getDisMax, updateDisMax, updateUserStatePromise} from "../../api";


function ChatRoom(props) {
    const [ws, setWs] = useState({})
    // 自己
    const [sender, setSender] = useState({name: props.match.params.name})

    let defaultUsers = []
    // 所有在线用户
    const [users, setUsers] = useState(defaultUsers)
    // send to state
    const [sendToUser, setSendToUser] = useState({})

    const [newMsgCountMap, setNewMsgCountMap] = useState({})

    const [clearMessageBoolean, setClearMessageBoolean] = useState(false)

    // 当前在线状态
    const [state, setState] = useState(3)

    const [time , setTime] = useState(getTime)

    function getTime() {
        let now = new Date();
        let year = now.getFullYear(); //得到年份
        let month = now.getMonth()+1;//得到月份
        let date = now.getDate();//得到日期
        let hour= now.getHours();//得到小时数
        if (hour < 10) hour = `0${hour}`
        let minute= now.getMinutes();//得到分钟数
        if (minute < 10) minute = `0${minute}`
        let second= now.getSeconds();//得到秒数
        if (second < 10) second = `0${second}`
        return `${year}/${month}/${date} ${hour}:${minute}:${second}`
    }
    setInterval(()=>{
        setTime(getTime())
    }, 1000)


    let isGroup = false
    const updateUser = (user)=>{
        for (let obj of users) {
            if (obj.name === user.name) {
                obj = user
                setUsers(users.slice())
                break
            }
        }
        updateSenderAvatar()
    }
    function getCurrentState() {
        for (let user of users) {
            if (user.name === sender.name) {
                return user.state
            }
        }
    }

    function updateCurrentState(state) {
        setState(state)
    }

    function newMsgCountUp(name) {
        if (name === sender.name) return
        let tmp = newMsgCountMap;
        tmp[name] = tmp[name]+1
        let target = Object.assign({}, tmp);
        setNewMsgCountMap(target)
        updateLocalDisMax()
    }

    function newMsgCountDown(name) {
        let tmp = newMsgCountMap;
        tmp[name] = 0
        let target = Object.assign({}, tmp);
        setNewMsgCountMap(target)
    }

    useDeepCompareEffect(()=>{
        console.log("newMsgCountMap updated !!!!!!!!!!!")
    },[newMsgCountMap])

    const addUser = (user)=> {
        //if (!user.avatar)user.avatar = getAvatar()
        // set
        for (let u of users) {
            if (u.name === user.name) {
                updateUser(user)
                return
            }
        }
        newMsgCountMap[user.name] = 0
        users.push(user)
        setUsers(users.slice())
        message.success(user.name+"已上线！");
    }
    function getAvatar() {
        let nextInt = Math.trunc(Math.random() * 100) % 10 + 1;
        return config.baseUrl + "i.pravatar.cc-" + nextInt + ".jpeg"
    }
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.watchPosition((position) => {
                let i = sender
                i.y = position.coords.latitude;
                i.x = position.coords.longitude;
                setSender(i)
            });
        } else {
            message.error("当前浏览器不支持获取位置！")
        }
    }
    function wsInit(avatar) {
        // if (ws.readyState && ws.readyState === ws.OPEN) ws.close()
        if (sender.x === undefined || sender.y === undefined) {
            sender.x = 0
            sender.y = 0
        }
        let baseUrl = config.baseUrl.replace("http","ws");
        let webSocket = new WebSocket(baseUrl + "test/one/" + sender.name +"/"  + avatar.replace(config.baseUrl, "") + "/" +sender.x + "/" + sender.y);
        setWs(webSocket)
    }

    // mounted hook
    useEffect(()=>{
        console.log("mounted")
        let senderJ  = sender
        senderJ.avatar = getAvatar()
        setSender(senderJ)
        getLocation()
        for (let user of users) {
            if (!user.avatar || user.name !== sender.name)user.avatar = getAvatar()
            updateUser(user)
        }
        setTimeout(()=>{
            wsInit(senderJ.avatar)
        },500)

    },[])

    function updateLocalDisMax() {
        getDisMax().then(res => {
            const parse = JSON.parse(res);
            console.log(parse)
            setInputValueD(parse.data)
        })
    }


    // users hook
    useEffect(()=> {
        updateCurrentState(getCurrentState())
    }, [users])



    // ws state监控
    useEffect(()=>{
        if (ws.readyState === undefined) return
        // if (ws.readyState === 3 || ws.readyState === 1) {
        //     setState(ws.readyState)
        // }
        console.log("当前ws状态：",ws.readyState)

    },[ws.readyState])

    function clearUsers() {
        setUsers([])
    }

    function updateSenderAvatar() {
        for (let user of users) {
            if (user.name === sender.name) {
                const newSender = sender
                newSender.avatar=user.avatar
                setSender(newSender)
            }
        }
    }

    // before destroy hook
    useEffect(()=>{
        return ()=>{
            //if (ws.readyState && ws.readyState === ws.OPEN)ws.close()
        }
    })
    let disableClass = !sendToUser.name ? "" : " stealth"

    function handleChange(e) {
        setState(e.value)
        if (e.value === 3) {
            updateUserStatePromise(sender.name, e.value).then(()=>ws.close())
        } else if (e.value === 1 && ws.readyState === 3){
            updateUserStatePromise(sender.name, e.value).then(()=>wsInit(sender.avatar))
        }else {
            updateUserStatePromise(sender.name, e.value).then()
        }
    }


    function onAfterChange() {

    }

    // 东经
    const [inputValueX, setInputValueX] = useState(100.13);
    // 北纬
    const [inputValueY, setInputValueY] = useState(52.3);

    const [inputValueD, setInputValueD] = useState(3000);

    const onChange = (value) => {
        if (isNaN(value)) {
            return;
        }
        setInputValueX(value);
    };

    const onChange1 = (value) => {
        if (isNaN(value)) {
            return;
        }
        setInputValueY(value);
    };

    function refreshState() {
        updateDisMax(inputValueD).then()
        if (ws !== undefined) {
            console.log("重连")
            let obj = sender
            obj.y = inputValueY;
            obj.x = inputValueX;
            setSender(obj)
            ws.close()
            wsInit(sender.avatar)
        }
    }


    function onChange2(val) {
        if (isNaN(val)) {
            return;
        }
        setInputValueD(val);
    }

    function refreshChat() {
        localStorage.clear()
        setSendToUser({})
    }

    return (
        <>
            <div className={"chatApp_tb"}>
                <div className={"chatApp_top"}>
                    <div className={"chatApp_top_left"}>
                        <div><button className={"chatApp_button_red"}></button></div>
                        <div><button className={"chatApp_button_yellow"}></button></div>
                        <div><button className={"chatApp_button_green"}></button></div>

                    </div>
                    <div className={"chatApp_top_mid"}>
                        <span>{time} </span>
                    </div>
                    <div className={"chatApp_top_right"}>
                        {/*<div className={"chatApp_state_title"}>在线状态</div>*/}

                        <span> 状态: </span>
                        <Select
                            labelInValue
                            defaultValue={{ value: state }}
                            style={{ width: 80 }}
                            onChange={handleChange}
                            value={state}

                        >
                            <Option value={1}><span className={"chatApp_green"}>在线</span></Option>
                            <Option value={2}><span className={"chatApp_warn"}>忙碌</span></Option>
                            <Option value={3}><span className={"chatApp_black"}>离线</span></Option>
                        </Select>
                    </div>
                </div>
                <Divider />
                <div className={"chatApp_listAndBox"}>
                    <div className={"chatApp_left"}>
                        <ChatListBox newMsgCountDown={newMsgCountDown} newMsgCountMap={newMsgCountMap} sendToUser={sendToUser} setSendToUser={setSendToUser} users={users}/>
                    </div>
                    <div className={"chatApp_right"}>
                        <ChatContent getTime={getTime} state={state} getCurrentState={getCurrentState} updateCurrentState={updateCurrentState} newMsgCountUp={newMsgCountUp} newMsgCountDown={newMsgCountDown} users={users} setUsers={setUsers}  setSendToUser={setSendToUser} clearUsers={clearUsers} clearMessageBoolean={clearMessageBoolean}  addUser={addUser}  updateUser={updateUser} ws={ws} isGroup={isGroup} sender={sender} sendToUser={sendToUser}/>
                        <div className={"chatApp__welcomeBottom" + disableClass}>
                        </div>
                    </div>
                    <div className={"test_option"}>
                        调试面板
                        <div>
                            东经
                        </div>
                        <Row>
                            <Col span={12}>
                                <Slider
                                    min={0}
                                    max={180}
                                    onChange={onChange}
                                    value={typeof inputValueX === 'number' ? inputValueX : 0}
                                    step={0.001}
                                />
                            </Col>
                            <Col span={4}>
                                <InputNumber
                                    min={0}
                                    max={180}
                                    style={{
                                        margin: '0 16px',
                                    }}
                                    step={0.001}
                                    value={inputValueX}
                                    onChange={onChange}
                                />
                            </Col>
                        </Row>
                        <div>
                            北纬
                        </div>
                        <Row>
                            <Col span={12}>
                                <Slider
                                    min={0}
                                    max={90}
                                    onChange={onChange1}
                                    value={typeof inputValueY === 'number' ? inputValueY : 0}
                                    step={0.001}
                                />
                            </Col>
                            <Col span={4}>
                                <InputNumber
                                    min={0}
                                    max={90}
                                    style={{
                                        margin: '0 16px',
                                    }}
                                    step={0.001}
                                    value={inputValueY}
                                    onChange={onChange1}
                                />
                            </Col>
                        </Row>
                        <div>
                            范围
                        </div>
                        <Row>
                            <Col span={12}>
                                <Slider
                                    min={0}
                                    max={5000}
                                    onChange={onChange2}
                                    value={typeof inputValueD === 'number' ? inputValueD : 0}
                                    step={1000}
                                />
                            </Col>
                            <Col span={4}>
                                <InputNumber
                                    min={0}
                                    max={5000}
                                    style={{
                                        margin: '0 16px',
                                    }}
                                    step={100}
                                    value={inputValueD}
                                    onChange={onChange2}
                                />
                            </Col>
                        </Row>
                        <button onClick={refreshState}>确认</button>
                        <button onClick={refreshChat}>一键清空聊天记录</button>
                    </div>
                </div>
            </div>
        </>

    );
}

export default ChatRoom;
